import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {RoleDetailService} from './role-detail.service';
import {CustomValidators} from '@kylin/validators';

@Component({
    selector: 'kylin-role-detail',
    templateUrl: './role-detail.component.html',
    styleUrls: ['../../user-managment/reset-password/reset-password.component.less']
})
export class RoleDetailComponent implements OnInit {
    @Input() isVisible;
    @Input() roleInfo: any;

    @Output() isVisibleChange = new EventEmitter<boolean>();
    @Output() processRstChange = new EventEmitter<boolean>();

    title: string;
    roleForm: FormGroup;
    editMode = false;
    loading = false;

    constructor(private fb: FormBuilder, private message: NzMessageService, private rolesv: RoleDetailService) {
    }

    ngOnInit() {
        this.editMode = !!this.roleInfo;
        this.title = this.editMode ? '修改角色' : ' 添加角色';
        this.roleForm = this.fb.group({
            code: [this.editMode ? this.roleInfo.code : '', Validators.required],
            name: [this.editMode ? this.roleInfo.name : '', Validators.required],
        })
    }

    // 关闭弹框
    closeModal(processRstChange?: boolean) {
        this.isVisible = false;
        this.isVisibleChange.emit(false);
        this.processRstChange.emit(processRstChange)
    }

    checkInput() {
        let {code, name} = this.roleForm.value;
        code = (code || '').trim();
        name = (name || '').trim();
        if (!code) {
            return '请输入角色编码';
        }
        if (!CustomValidators.checkCode(code)) {
            return '角色编码为大写字母组成';
        }
        if (!name) {
            return '请输入角色'
        }
    }

    submit() {
        const checkMess = this.checkInput();
        if (checkMess) {
            this.message.warning(checkMess);
            return;
        }
        this.loading = true;
        if (this.editMode) {
            this.roleForm.value.id = this.roleInfo.id;
        }
        this.rolesv.addRole(this.roleForm.value).then(rep => {
            if (rep.resp_code === '10000') {
                this.message.success(this.editMode ? `修改角色 ${this.roleForm.get('name').value} 成功` : `添加角色 ${this.roleForm.get('name').value} 成功`);
                this.closeModal(true);
            } else {
                this.message.error(this.editMode ? `修改角色失败，${rep.resp_msg}` : `添加角色失败，${rep.resp_msg}`);
            }
            this.loading = false;
        })
    }
}
